package staticPage;


import java.util.List;
import javax.el.ELException;
import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import lecture.LectureManagedBean;

/**
 * 
 * @author Thorsten Ludwig
 */
@ManagedBean(name="staticPageBean")
@CustomScoped(value="#{window}")
public class StaticPageManagedBean {
    
    @ManagedProperty(value="#{param.staticPageName}")
    private String staticPageName;
    
    private LectureManagedBean lecture;
    
    private boolean edit;
    
    private StaticPage page;
    
    public StaticPageManagedBean() {
        FacesContext context = FacesContext.getCurrentInstance();
        LectureManagedBean lb = (LectureManagedBean) context.getApplication().evaluateExpressionGet(context, "#{lectureBean}", LectureManagedBean.class);
        this.lecture = lb;
        initPageName();
    }

    private void initPageName() throws ELException {
            String link = this.lecture.getSelectedSubCategory().getLink();        
            //"staticPage.jsf?staticPageName="
            this.setStaticPageName(link.substring(30));
    }

    public String getStaticPageName() {
        this.initPageName();
        return staticPageName;
    }

    public void setStaticPageName(String name) {
        System.out.println("");
        System.out.println("Name der Seite: " + name);
        System.out.println("");
        this.staticPageName = name;
        this.page = getStaticPage(name);
    }
    
    public String getContent() {
       // this.initPageName();
        if (this.page == null)
            return "Fehler: Content konnte nicht ermittelt werden";
        System.out.println("Content wird zurückgegeben");
        return this.page.getContent();
    }
    
    public void setContent(String content) {
        this.page.setContent(content);
    }

    public boolean isEdit() {
        return edit;
    }

    private StaticPage getStaticPage(String name) {
        List<StaticPage> pages = this.lecture.getLecture().getStaticPages();
        for (StaticPage s: pages) {
            if (s.getName().equalsIgnoreCase(name)) {
                return s;
            }
        }
        return null;
    }
    
    public void toggle() {
        this.edit = !this.edit;
    }
}
